#include "wskserver.h"
#include <nlohmann/json.hpp>

using websocketpp::lib::placeholders::_1;
using websocketpp::lib::placeholders::_2;
using namespace std;
using namespace nlohmann;

//
// Created by yorkc on 2023/12/18.
//
wskserver::wskserver() {

    //设置日志记录设置
    wbserver_endpoint.set_error_channels(websocketpp::log::elevel::all);
    wbserver_endpoint.set_access_channels(websocketpp::log::alevel::all ^ websocketpp::log::alevel::frame_payload);
    //连接建立处理函数
    wbserver_endpoint.set_open_handler(bind(&wskserver::on_open, this, ::_1));
    //连接断开处理函数
    wbserver_endpoint.set_close_handler(bind(&wskserver::on_close, this, ::_1));
    //报文处理函数
    wbserver_endpoint.set_message_handler(bind(&wskserver::handmsg, this, ::_1, ::_2));
}

void wskserver::run() {
    wbserver_endpoint.init_asio();

    // Listen on port 9002
    wbserver_endpoint.listen(9002);

    wbserver_endpoint.set_reuse_addr(true);
    // Start the server accept loop
    wbserver_endpoint.start_accept();
//    wbserver_endpoint.set_pong_timeout();
//    wbserver_endpoint.set_open_handshake_timeout()
    // Start the ASIO io_service run loop
    wbserver_endpoint.run();
}

void wskserver::on_open(websocketpp::connection_hdl hdl) {
    cout << "websocket client has already been opened:" << hdl.lock().get() << endl;
    // 根据连接句柄获得连接对象
    server::connection_ptr con = wbserver_endpoint.get_con_from_hdl(hdl);
    // 获得URL路径
    std::string path = con->get_resource();
    wbserver_endpoint.get_alog().write(websocketpp::log::alevel::app, "Connected to path " + path);
}

void wskserver::on_close(websocketpp::connection_hdl hdl) {
    cout << "websocket client has already been closed:" << hdl.lock().get() << endl;
}

void wskserver::handmsg(websocketpp::connection_hdl hdl, server::message_ptr msg) {
    cout << "on_message called with hdl: " << hdl.lock().get();
    cout << "receive message:" << msg->get_payload() << endl;
    cout << "receive message ops:" << msg->get_opcode() << endl;
    json payload = json::parse(msg->get_payload());
    int code;
    payload.at("code").get_to(code);
    cout<<"code:"<<code<<endl;
    sendmsg(hdl, msg->get_opcode(), "fky");
}

void wskserver::sendmsg(websocketpp::connection_hdl hdl, websocketpp::frame::opcode::value ops, const string &msgcontent) {
    wbserver_endpoint.send(hdl, msgcontent, ops);
}
